package com.friendview;

import java.io.*;
import java.net.*;
import java.sql.*;
import java.util.*;

import android.app.*;
import android.content.*;
import android.content.DialogInterface.OnClickListener;
import android.graphics.*;
import android.net.*;
import android.os.*;
import android.support.v4.app.ListFragment;
import android.util.*;
import android.view.*;
import android.widget.*;

import com.formen.ndk.*;

public class FriendListView extends ListFragment {

	static String[] MOBILE_OS = null;
	static String[] statusMsg = null;
	ProgressDialog pBar;

	ArrayList<Bitmap> bitArr = new ArrayList<Bitmap>();
	Bitmap imgBitmap = null;
	String urlPath = "http://ce.sejong.ac.kr/~firebat/uploads/";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// setListAdapter(new ArrayAdapter<String>(this, R.layout.list_mobile,
		// R.id.label, MOBILE_OS));

		pBar = ProgressDialog.show(getActivity(), "", "잠시만 기다려주세요.");
		BackThread backt1 = new BackThread();
		backt1.setDaemon(true);
		backt1.start();

	}

	@Override
	public void onListItemClick(ListView l, View v, int position, long id) {

		// get selected items
		final String selectedValue = (String) getListAdapter()
				.getItem(position);
		if (position != 0) {
			AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
			builder.setTitle(selectedValue.split("\t")[1]);
			builder.setMessage("최근 만난 날 : "
					+ selectedValue.split("\t")[5].substring(0, 10)
					+ "\n만난 장소 : " + selectedValue.split("\t")[6]);
			builder.setPositiveButton("Call", new OnClickListener() {

				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					Uri uri = Uri.parse("tel: 0" + selectedValue.split("\t")[2]);
					Intent intent = new Intent(Intent.ACTION_DIAL, uri);
					startActivity(intent);
				}
			});
			builder.setNeutralButton("Message", new OnClickListener() {

				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					Intent intent = new Intent(Intent.ACTION_VIEW);
					intent.putExtra("sms_body",
							selectedValue.split("\t")[5].substring(5, 7) + "월 "
							+ selectedValue.split("\t")[5].substring(8, 10) + "일날 "
									+ selectedValue.split("\t")[6] + "에서 만난 "
									+ MainActivity.user_name + "입니다.");
					intent.putExtra("address", " 0"
							+ selectedValue.split("\t")[2]);

					intent.setType("vnd.android-dir/mms-sms");
					startActivity(intent);
				}
			});
			builder.setNegativeButton("Cancel", new OnClickListener() {

				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub

				}
			});

			builder.show();
		} else {
			Toast.makeText(getActivity(), "아래에서 고르세요", Toast.LENGTH_SHORT)
					.show();
		}

	}

	String[] getFriendList() {
		String path = Environment.getExternalStorageDirectory()
				+ "/E-Profile/user_information/user_log.txt";
		File dir = new File(path);
		BufferedReader br;
		String str;
		ArrayList<String> strArr = new ArrayList<String>();
		String[] strArr2;

		try {
			if (dir.exists())
				br = new BufferedReader(new FileReader(dir));
			else
				br = new BufferedReader(new FileReader(dir));

			while ((str = br.readLine()) != null) {
				while (!str.split("\t")[0].equals(MainActivity.user_id)) {
					strArr.add(str);
					break;
				}
			}
			br.close();
		} catch (FileNotFoundException e) {
			Log.d("filterDuplicate", e.toString());
		} catch (IOException e) {
			Log.d("filterDuplicate", e.toString());
		}

		strArr2 = new String[strArr.size()];
		strArr2 = strArr.toArray(strArr2);

		/*
		 * return 0 : no problem return 1 :
		 */
		strArr2 = getStatusMsg(strArr2);

		return strArr2;
	}

	String[] getStatusMsg(String[] id) {
		String[] tmp = id.clone();

		try {
			Class.forName("com.mysql.jdbc.Driver");

		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Connection conn = null;
		Statement stmt = null;
		ResultSet rs = null;
		String query = "";

		try {
			String jdbcDriver = "jdbc:mysql://sce.sejong.ac.kr:3306/firebat?"
					+ "useUnicode=true&characterEncoding=utf8";
			String dbUser = "firebat";
			String dbPass = "a1852411";

			// 2.
			conn = DriverManager.getConnection(jdbcDriver, dbUser, dbPass);

			// 3.
			stmt = conn.createStatement();

			statusMsg = new String[tmp.length];
			statusMsg[0] = "Status";
			for (int i = 1; i < tmp.length; i++) {
				query = "select status_msg from nfc_user where user_id='"
						+ tmp[i].split("\t")[0] + "'";
				rs = stmt.executeQuery(query);
				if (rs.next())
					statusMsg[i] = rs.getString("status_msg");
			}

		} catch (SQLException ex) {
			pBar.dismiss();
			Toast.makeText(getActivity(), "친구목록 가져오기 실패", Toast.LENGTH_SHORT)
					.show();
			ex.printStackTrace();
		} finally {
			// 6.
			if (rs != null)
				try {
					rs.close();
				} catch (SQLException ex) {
				}
			if (stmt != null)
				try {
					stmt.close();
				} catch (SQLException ex) {
				}

			// 7.
			if (conn != null)
				try {
					conn.close();
				} catch (SQLException ex) {
				}
		}

		return tmp;
	}

	class BackThread extends Thread {
		public void run() {
			MOBILE_OS = getFriendList();
			if (MainActivity.bitArr.isEmpty()) {
				bitArr.add(null);
				ImgThread img1 = new ImgThread();
				img1.setDaemon(true);
				img1.start();
			}
			mHandler.post(new Runnable() {
				public void run() {
					pBar.dismiss();
					if (MainActivity.bitArr.isEmpty())
						MainActivity.bitArr = bitArr;
					setListAdapter(new FriendArrayAdapter(getActivity(),
							MOBILE_OS, statusMsg));
				}
			});
		} // run
	} //

	Handler mHandler = new Handler();

	class ImgThread extends Thread {
		public void run() {
			for (int i = 1; i < MOBILE_OS.length; i++) {
				imgBitmap = ProfileImage(urlPath + MOBILE_OS[i].split("\t")[0]
						+ ".png");
				bitArr.add(imgBitmap);
			}
			// 반복문으로 이미지 받아오고 어레이에 등록
		}
	}

	private Bitmap ProfileImage(String strImageURL) {
		Bitmap imgBitmap = null;

		try {
			URL url = new URL(strImageURL);
			URLConnection conn = url.openConnection();
			conn.connect();

			int nSize = conn.getContentLength();
			BufferedInputStream bis = new BufferedInputStream(
					conn.getInputStream(), nSize);
			imgBitmap = BitmapFactory.decodeStream(bis);
			MainActivity.imgBitmap = imgBitmap;
			bis.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return imgBitmap;

	}

}